<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/controller/ctlAbstract.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busOccupation.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAddress.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busResource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAvatar.php';
									
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/user.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/address.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/avatar.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/simpleImage.php';

/**
 * This is the class handle the registration of new users
 */
class RegisterController extends AbstractController {
	private $_userBus;
	private $_addressBus;
	private $_resourceBus;
	private $_avatarBus;
	private $_occupationBus;
	
	/**
	 *
	 * This is the default function that will be called by the router
	 * @param array $getVars GET variables posted to index.php
	 */
	public function main(array $getVars) {
		global $ubi;
		
		$this->_userBus = new UserBus();
		$this->_addressBus = new AddressBus();
		$this->_resourceBus = new ResourceBus();
		$this->_avatarBus = new AvatarBus();
		$this->_occupationBus = new OccupationBus();
		
		//error list when adding user
		$errList = array();
			
		//register user
		if (isset($_POST['txtUserName']) && isset($_POST['txtPassword']) && isset($_POST['txtEmail']) && isset($_POST['selGender']) && isset($_POST['txtCode']) && isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtDOB']) && isset($_POST['txtNumber']) && isset($_POST['txtStreet']) && isset($_POST['txtWard']) && isset($_POST['txtDistrict']) && isset($_POST['selCity'])) {
			$user = new UserModel();

			//check captcha code
			require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/captcha/securimage.php';
			$img = new Securimage();
			$valid = $img->check($_POST['txtCode']);

			//if the code is valid
			if ($valid == true) {
				if ($this->_userBus->isEmailExisted($_POST['txtEmail'])) {
					$errList[] = 'Email này đã có người đăng ký. Bạn hãy đăng ký với một email khác !!!';					
				} else {				
					//read address data
					$address = new AddressModel();
					$address->setDistrict($_POST['txtDistrict']);
					$address->setNumber($_POST['txtNumber']);
					$address->setStreet($_POST['txtStreet']);
					$address->setWard($_POST['txtWard']);
					$address->setCity($_POST['selCity']);
					$address->setLongitude(0);
					$address->setLatitude(0);
					$address->setType($ubi['LOCATION']['USER']);
	
					$addressID = $this->_addressBus->addAddress($address);
					
					//if insert address successfully, insert new user
					if ($addressID != 0) {					
						$user->setUserName($_POST['txtUserName']);
						$user->setPasswordHash($_POST['txtPassword']);
						$user->setEmail($_POST['txtEmail']);
						$user->setFirstName($_POST['txtFirstName']);
						$user->setLastName($_POST['txtLastName']);
						$user->setDateOfBirth(GeneralFunctions::getDate($_POST['txtDOB']));
						$user->setGender($_POST['selGender']);
						$user->setEmail($_POST['txtEmail']);
						$user->setTelephone($_POST['txtPhone']);
						$user->setCellPhone($_POST['txtCellPhone']);
						$user->setOccupationID($_POST['selOccupation']);
						$user->setAddressID($addressID);
						$user->setBlast($_POST['txtBlast']);
						
						//create an activation code for user
						$activation_code = GeneralFunctions::createRandomCode();
//						$activation_code = $this->createActivationCode();
						$user->setActivationCode($activation_code);
	
						$userID = $this->_userBus->addUser($user);
						
						if ($userID != 0) {
							if ($_FILES['img']['error'] > 0) {
								$errList[] = 'Có lỗi khi upload hình';
							} else {
								$fileName = $_FILES['img']['name'];
								if (file_exists($ubi['SERVER']['SERVER_ROOT'] . RESOURCE_PATH . '/' . $fileName)) { //file avatar existed
									$fileName = StringUtil::changeFileName($fileName);
								}
								
								//create resource model object
								$res = new ResourceModel();
								$res->setResourceName($fileName);
								$res->setShortDescription('avatar');
								
								$fileSavedResourceName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $fileName;
								$fileSavedThumbnailName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $fileName;
								$resOK = false;							
								if (move_uploaded_file($_FILES['img']['tmp_name'], $fileSavedResourceName)) {
									copy($fileSavedResourceName, $fileSavedThumbnailName);								
									//create resource bus object
									$resID = $this->_resourceBus->addResource($res);
		
									//add avatar into resource successfully
									if ($resID != 0) {
										$image = new SimpleImage();
										$image->load($fileSavedThumbnailName);
										$image->resize($ubi['SITE']['WIDTH_THUMBNAIL'], $ubi['SITE']['HEIGHT_THUMBNAIL']);
										$image->save($fileSavedThumbnailName);
				
										$image->load($fileSavedResourceName);
										$image->resize($ubi['SITE']['WIDTH_RESOURCE'], $ubi['SITE']['HEIGHT_RESOURCE']);
										$image->save($fileSavedResourceName);
										
										$resOK = true;
										$avatar = new AvatarModel();
										$avatar->setUserID($userID);
										$avatar->setResourceID($resID);
										
										$this->_avatarBus->addAvatar($avatar);
									} 
								} 
								if (!$resOK) {
									$errList[] = "Không upload avatar được.";
								}
							}
							
							$notice = "RegisterSuccessfully";
							include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewNotice.php';
							
							//send email to the user with activation code
							$to = $_POST["txtEmail"];
							
							$subject = "Chào mừng bạn đến với " . $ubi['SERVER']['SITE_NAME'];
							
							$message = "Chào mừng bạn " . $user->getFirstName() . " " . $user->getLastName() . " đã đến với " . $ubi['SERVER']['SITE_NAME'] . "!<br />\n" .
	"Đây là email kích hoạt tài khoản " . $ubi['SERVER']['SITE_NAME'] . " của bạn<br />\n" .
	"Bạn đã đăng ký thành viên thành công tại <a href=\"" . $ubi['SERVER']['SITE_ROOT'] . "\">" . $ubi['SERVER']['SITE_NAME'] . "</a>. Bạn hãy hoàn tất quá trình đăng ký bằng việc click vào link kích hoạt sau: <a href='" . $ubi['SERVER']['SITE_ROOT'] . "index.php?Activate&code=" . $user->getActivationCode() . "'>kích hoạt</a><br />\n" .
	"Tên tài khoản của bạn: " . $user->getUserName() . "<br />\n" .
	"Mã tài khoản của bạn: " . $user->getPasswordHash() . "<br />\n" .
	"Xin cảm ơn và chào mừng bạn đến với <a href=\"" . $ubi['SERVER']['SITE_ROOT'] . "\">" . $ubi['SERVER']['SITE_NAME'] . "</a>";
							
							$headers = "From: " . $ubi['SERVER']['SITE_NAME'] . "<" . $ubi['SERVER']['ADMIN_EMAIL'] . ">";
							
							GeneralFunctions::ubiMail($to, $subject, $message);							
							return;
						} else {
							$errList[] = 'Có lỗi xảy ra khi thêm user vào CSDL';
							//include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewRegister.php';
						}
					} else {
						$errList[] = 'Có lỗi xảy ra khi thêm địa chỉ vào CSDL';
						$this->_addressBus->deleteAddress($addressID);
					}
				}
			} else {
				$errList[] = 'Mã bảo vệ không chính xác';
			}
		}
		//get list of occupations
		$occupationList = $this->_occupationBus->getOccupationList();
				
		include $ubi['SERVER']['SERVER_ROOT'] .  '/view/viewRegister.php';
	}
	
	/**
	 * 
	 * This function is used to create Activation Code according to current time 
	 * @param $username username of the user that we want to create activation code for
	 */
	protected function createActivationCode() {
		//begin of method createActivationCode		
		//get the unix current time
		$time = time();
		
		//declare the code variable to hold the code that will be created
		$code = "";
		
		//iterate through each character in $username
		for ($i = 0; $i < 20 - strlen($time); $i++) {
		//begin of for $i
			
			//get the random value from mt_rand
			//the value will be from 0 to 35
			$rvalue = mt_rand(0, 35);
			
			//if the value in the range of 0 to 25, we will convert it to alphabet character
			//by adding 97 to its ascii code
			//if the value is greater than 25, we will convert it to numeric character
			//by adding 22 to its ascii code
			if ($rvalue < 26){
				$code .= chr($rvalue + 97);
			} else {
				$code .= chr($rvalue + 22);
			}			
		}//end of for $i
		
		//add the unix time to the code
		$code .= $time;
		
		return $code;
	}//end of method createActivationCode
}
?>